#import "Common.h"
#import "DataType.h"
#import "LayerStore.h"
#import "SpellSlot.h"
#import "LayerBuy.h"
#import "BtnGold.h"
#import "DataSL.h"

// 商店售卖顺序
static const SpellType sSpellType[SPELL_COUNT] =
	{ ST_Small, ST_Rare, ST_Burst, ST_Freeze, ST_Double, ST_Shield, ST_Bomb, ST_Bless, ST_Angel };
static const CGPoint sShopItemPos[2] = { ccp(70,30), ccp(410,30) };
static const NSString* sShopBtnLabel[2] = { @"BtnCancel", @"BtnConfirm" };

@implementation LayerStore

-(id)initWithParent:(CCLayer*)parent
{
	if((self = [super init])) {
		mParentLayer = parent;

		// 出现动画
		self.position = ccp(480,0);
		[self runAction:
		 [CCSequence actions:
		  [CCEaseBounceOut actionWithAction:[CCMoveTo actionWithDuration:0.5 position:CGPointZero]],
		  [CCCallFunc actionWithTarget:self selector:@selector(layerEntered)],NULL]];
		
		CCLayerColor* layerBg = [CCLayerColor layerWithColor:ccc4(0,0,0,255)];
		[self addChild:layerBg];

		// 初始化
		mIsDrag = false;
		mDragFrom = 0;
		for(int i=0; i<SPELLSLOT_COUNT; i++)
			mBuyType[i] = ST_None;
		mDragIdx = -1;
		mTotalCost = 0;

		// background
		CCSprite* bg = [CCSprite spriteWithFile:@"background.png"];
		bg.position = gPointCenter;
		bg.opacity = 100;
		[self addChild:bg];
		
		// Title
   		CCLabelTTF* title = [CCLabelTTF labelWithString:NSLocalizedString(@"StoreTitle",nil)
											   fontName:gFontName
											   fontSize:30];
		title.position = ccp(240,300);
		title.color = ccGREEN;
		[self addChild:title];

		mBtnGold = [BtnGold node];
		mBtnGold.position = ccp(450,290);
		[self addChild:mBtnGold];
		
		// 魔法槽
		mSpellSlot = [SpellSlot node];
		[self addChild:mSpellSlot];

		// shop
		int startPosX = 40+gSettingData.startPosX;
		int startPosY = 250;
		
		mShopItems = [[NSMutableArray alloc] init];
		
		CCTexture2D* goldTex = [[CCTextureCache sharedTextureCache] addImage:@"GoldCoin.png"];
	
		for(int i=0; i<SPELL_COUNT; i++) {
			Spell* spell = [[Spell alloc] initWithType:sSpellType[i] trans:false];
			spell.position = ccp(startPosX+(i%3)*130, startPosY-(i/3)*50);
			spell.scale = 0.8;
			[self addChild:spell];
			
			[mShopItems addObject:spell];

			CCSprite* goldIcon = [CCSprite spriteWithTexture:goldTex];
			goldIcon.position = ccp(startPosX+25+(i%3)*130, startPosY-11-(i/3)*50);
			goldIcon.anchorPoint = gAnchorLeft;
			goldIcon.scale = 0.85;
			[self addChild:goldIcon];
			
			CCLabelTTF* labelSpell = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%@\n    : %d", NSLocalizedString(spell.spellName,nil), spell.sell]
													  dimensions:CGSizeMake(100,60)
													   alignment:CCTextAlignmentLeft
														fontName:gFontName
														fontSize:16];
			labelSpell.color = ccYELLOW;
			labelSpell.anchorPoint = gAnchorLeft;
			labelSpell.position = ccp(startPosX+25+(i%3)*130, startPosY-13-(i/3)*50);
			[self addChild:labelSpell];
		}
		
		// 拖拽中魔法
		mDragSpell = [[Spell alloc] initWithType:ST_None trans:false];
		mDragSpell.visible = false;
		[self addChild:mDragSpell z:10001];

		// 说明背景
		CCLayerColor* board = [CCLayerColor layerWithColor:ccc4(0,200,0,50) width:380 height:65];
		board.position = ccp(startPosX-20,55);
		[self addChild:board];

		// 说明标题
		mLabelName = [CCLabelTTF labelWithString:NSLocalizedString(@"StoreDescNameDefault",nil)
										fontName:gFontName
										fontSize:16];
		mLabelName.color = ccMAGENTA;
		mLabelName.position = ccp(startPosX+170,105);
		[self addChild:mLabelName];
		
		// 说明内容
		mLabelDesc = [CCLabelTTF labelWithString:NSLocalizedString(@"StoreDescDefault",nil)
									  dimensions:CGSizeMake(360,50)
									   alignment:CCTextAlignmentCenter
										fontName:gFontName 
										fontSize:14];
		mLabelDesc.color = ccYELLOW;
		mLabelDesc.position = ccp(startPosX+170,70);
		[self addChild:mLabelDesc];
		
		// 说明持续时间
		mLabelDuration = [CCLabelTTF labelWithString:@"" fontName:gFontName fontSize:14];
		mLabelDuration.color = ccMAGENTA;
		mLabelDuration.anchorPoint = gAnchorRight;
		mLabelDuration.position = ccp(startPosX+350,105);
		[self addChild:mLabelDuration];

		mLabelCost = [CCLabelTTF labelWithString:[NSString stringWithFormat:NSLocalizedString(@"StoreTotalCost",nil), commaprint(0)]
										fontName:gFontName
										fontSize:20];
		mLabelCost.color = ccYELLOW;
		mLabelCost.anchorPoint = gAnchorRight;
		mLabelCost.position = ccp(350,30);
		[self addChild:mLabelCost];

		// 按钮
		CCMenu* menu = [CCMenu menuWithItems:NULL];
		menu.position = CGPointZero;
		[self addChild:menu];
		
		CCMenuItemImage* menuItem;
		for(int i=0; i<2; i++) {
			menuItem = [CCMenuItemImage itemFromNormalImage:@"btn-02.png"
											  selectedImage:@"btn-02-s.png"
													 target:self
												   selector:@selector(callMenu:)];
			menuItem.position = sShopItemPos[i];
			[menu addChild:menuItem z:i+1000];
			
			CCLabelTTF* itemLabel = [CCLabelTTF labelWithString:NSLocalizedString(sShopBtnLabel[i],nil)
													   fontName:gFontName
													   fontSize:16];
			itemLabel.position = ccp(menuItem.contentSize.width/2,menuItem.contentSize.height/2+2);
			[menuItem addChild:itemLabel];
		}
	}
	return self;
}

-(void)dealloc
{
	[mShopItems release];
	[super dealloc];
}

-(void)layerEntered
{
	mParentLayer.visible = false;
	[self setIsTouchEnabled:YES];
}

-(void)callMenu:(CCMenuItem*)sender
{
	int id = [sender zOrder];

	[[SimpleAudioEngine sharedEngine] playEffect:SOUND_BTN01];
	
	switch(id) {
		case 1000:		// Cancel
			[self closeLayer];
			break;
		case 1001:		// Confirm
			if(mTotalCost <= gGlobalData.gold) {			// 钱够
				[[SimpleAudioEngine sharedEngine] playEffect:EF_COIN];
				gGlobalData.gold -= mTotalCost;
				for(int i=0; i<SPELLSLOT_COUNT; i++) {
					gGlobalData.spells[i] = [mSpellSlot spell:i].sType;
					if(mBuyType[i] != ST_None)
						gGlobalData.totalBuyCount ++;
				}

				[gGCManager reportAm:14 percent:MIN(100,gGlobalData.totalBuyCount*5)];		// 成就14，购物者

				gSaveData();
				[self closeLayer];
			} else {
				UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"MoreGold",nil)
																message:NSLocalizedString(@"StoreMoreGoldMsg",nil)
															   delegate:self
													  cancelButtonTitle:NSLocalizedString(@"BtnNo",nil)
													  otherButtonTitles:NSLocalizedString(@"BtnYes",nil), nil];
				alert.tag = 2;
				[alert show];
				[alert release];
			}
			break;
	}
}

-(void) destroyDrag
{
	[mDragSpell change:ST_None];
	mDragSpell.visible = false;
}

-(void) restoreDrag
{
	[mDragSpell runAction:[CCSequence actions:[CCSpawn actions:[CCMoveTo actionWithDuration:0.1f position:mDragOriPos],[CCScaleTo actionWithDuration:.1f scale:1], NULL],[CCCallFunc actionWithTarget:self selector:@selector(destroyDrag)], NULL]];
}

-(void)closeLayer
{
	mParentLayer.visible = true;
	[self runAction:[CCSequence actions:[CCMoveTo actionWithDuration:0.3 position:ccp(580,0)],
		[CCCallFunc actionWithTarget:self selector:@selector(destroyLayer)],NULL]];
}

-(void)destroyLayer
{
	[mParentLayer onEnter];
	[self.parent removeChild:self cleanup:true];
}

#pragma mark -
#pragma mark Delegate

-(void)registerWithTouchDispatcher
{
	[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}

-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(buttonIndex == 1) {
		NSInteger alertTag = [alertView tag];
		switch(alertTag) {
			case 2: 	// 跳转到购买界面
				[self onExit];
				[[[CCDirector sharedDirector] runningScene] addChild:
				 [[[LayerBuy alloc] initWithParent:self] autorelease] z:50000];
				break;
			case 1:		// 交换丢弃
				if(mBuyType[mDragIdx] != ST_None)
					mTotalCost -= [mSpellSlot spell:mDragIdx].sell;
				mTotalCost += mDragSpell.sell;
				[mSpellSlot changeSpell:mDragIdx type:mDragSpell.sType];
				mBuyType[mDragIdx] = mDragSpell.sType;
				[self destroyDrag];
				mLabelCost.string = [NSString stringWithFormat:NSLocalizedString(@"StoreTotalCost",nil), commaprint(mTotalCost)];
				break;
			case 0:		// 直接丢弃
				[mSpellSlot changeSpell:mDragIdx type:ST_None];
				break;
		}
	}
	else {
		[self destroyDrag];
	}

}

-(BOOL)ccTouchBegan:(UITouch*)touch withEvent:(UIEvent*)event;
{
	if(mIsDrag)
		return false;
	
	// 检查是否从商店拖拽
	SpellType dragType;
	for(uint i=0; i<[mShopItems count]; i++) {
		Spell* s = (Spell*)[mShopItems objectAtIndex:i];
		if([s checkClick:touch]) {
			mIsDrag = true;
			dragType = s.sType;
			mDragOriPos = s.position;
			mDragFrom = 0;
			break;
		}
	}
	
	// 检查是否从魔法槽拖拽
	if(!mIsDrag) {
		int idx = [mSpellSlot checkClick:touch];
		if(idx >= 0) {
			if([mSpellSlot spell:idx].sType != ST_None) {
				mIsDrag = true;
				dragType = [mSpellSlot spell:idx].sType;
				mDragIdx = idx;
				mDragOriPos = [mSpellSlot spellPos:idx];
				mDragFrom = 1;
			}
		}
	}
	
	if(mIsDrag) {
		[mDragSpell change:dragType];
		mDragSpell.position = [self convertTouchToNodeSpace:touch];
		mLabelName.string = mDragSpell.spellName;
		mLabelDesc.string = mDragSpell.desc;
		mLabelDuration.string = [mDragSpell durationStr];
	}	else {
		mLabelName.string = NSLocalizedString(@"StoreDescNameDefault",nil);
		mLabelDesc.string = NSLocalizedString(@"StoreDescDefault",nil);
		mLabelDuration.string = @" ";
	}
	
	return true;
}

-(void)ccTouchMoved:(UITouch*)touch withEvent:(UIEvent*)evt
{
	if(mIsDrag) {
		mDragSpell.position = [self convertTouchToNodeSpace:touch];
		if(ccpDistance(mDragSpell.position, mDragOriPos) >= 15)
			mDragSpell.visible = true;
	}
}

-(void)ccTouchEnded:(UITouch*)touch withEvent:(UIEvent*)evt
{
	if(mIsDrag) {
		CGPoint posTouch = [self convertTouchToNodeSpace:touch];
		
		if(mDragFrom == 0) {													// 从商店拖来的
			int targetIdx = [mSpellSlot checkClick:touch];
			if(targetIdx >= 0) {												// 拖到某栏位上了
				[[SimpleAudioEngine sharedEngine] playEffect:SOUND_BTN02];

				Spell* spell = [mSpellSlot spell:targetIdx];
				if(spell.sType != ST_None) {									// 此栏位有以前剩下的
					mDragIdx = targetIdx;
					mIsDrag = false;
					NSString* msg = [NSString stringWithFormat:NSLocalizedString(@"StoreDropSpellMsg",nil),
									 NSLocalizedString(spell.spellName,nil)];
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"StoreDropSpell",nil)
																	message:msg
																   delegate:self
														  cancelButtonTitle:NSLocalizedString(@"BtnNo",nil)
														  otherButtonTitles:NSLocalizedString(@"BtnYes",nil), nil];
					alert.tag = 1;
					[alert show];
					[alert release];
				} else {
					mTotalCost += mDragSpell.sell;
					[mSpellSlot changeSpell:targetIdx type:mDragSpell.sType];
					mBuyType[targetIdx] = mDragSpell.sType;
					[self destroyDrag];
				}
			}
			else
				[self restoreDrag];
		} else {																													// 从栏位中拖出来的
			int targetIdx = [mSpellSlot checkClick:touch];
			if(targetIdx == mDragIdx)																				// 没变，恢复
				[self restoreDrag];
			else if(targetIdx >= 0) {																				// 拖到某栏位上了, 交换位置
				[[SimpleAudioEngine sharedEngine] playEffect:SOUND_BTN02];
				[mSpellSlot changeSpell:mDragIdx type:[mSpellSlot spell:targetIdx].sType];
				[mSpellSlot changeSpell:targetIdx type:mDragSpell.sType];
				mBuyType[mDragIdx] = mBuyType[targetIdx];
				mBuyType[targetIdx] = mDragSpell.sType;
				[self destroyDrag];
			} else {																												// 卖掉该物品
				[[SimpleAudioEngine sharedEngine] playEffect:SOUND_BTN02];
				if(mBuyType[mDragIdx] != ST_None) {														// 此栏位是新买的东西
					mTotalCost -= mDragSpell.sell;
					mBuyType[mDragIdx] = ST_None;
					[mSpellSlot changeSpell:mDragIdx type:ST_None];
				} else {
					NSString* msg = [NSString stringWithFormat:NSLocalizedString(@"StoreDorpDirectMsg",nil),
									 NSLocalizedString(mDragSpell.spellName,nil)];
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"StoreDropSpell",nil)
																	message:msg
																   delegate:self
														  cancelButtonTitle:NSLocalizedString(@"BtnNo",nil)
														  otherButtonTitles:NSLocalizedString(@"BtnYes",nil), nil];
					alert.tag = 0;
					[alert show];
					[alert release];
				}
				[self destroyDrag];
			}
		}
		
		mLabelCost.string = [NSString stringWithFormat:NSLocalizedString(@"StoreTotalCost",nil), commaprint(mTotalCost)];
		mIsDrag = false;
	}
}

-(void) ccTouchCancelled:(UITouch*)touch withEvent:(UIEvent*)evt
{
	if(mIsDrag)
	{
		[self restoreDrag];
//		CCLOG(@"Touch Canceled");
		mIsDrag = false;
	}
}

@end
